package com.glamour.hlcity.component.log.util;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * 日志管理
 * @author zhaoxing.luizx
 */
public final class LogTracker {

  
    private static ThreadLocal<LogContext> logContextThread = new ThreadLocal<LogContext>();

    private LogTracker() {
    }

    public static class LogContext {

        private static final String KEY_PURPOSE        = "请求目的";
        private static final String PREFIX_OF_FEATURES = "~";
        private static final String SUFFIX_OF_FEATURES = "~";
        private static final String EMPTY_FEATURES     = PREFIX_OF_FEATURES + "{}"
                                                               + SUFFIX_OF_FEATURES;
        private Map<String, String> clues              = new LinkedHashMap<String, String>();

        /**
         * 增加日志特征值，特征值在一次请求的所有日志都会被输出 提供给自动化工具进行分析
         * @param key
         * @param value
         * @return
         */
        public LogContext addClue(String key, String value) {
            clues.put(key, value);
            return this;
        }

       

        /**
         * 设置本次请求目的，这是一种特殊的日志特征值，用来标示请求所做的操作。 为完成这次操作所打印的日志都被标示为同一目的。
         * 请求目的一般在入口处设值（如在提供给外部系统调用的接口实现中设值）。
         * @param purpose
         * @return
         */
        public LogContext setPurpose(String purpose) {
            clues.put(KEY_PURPOSE, purpose);
            return this;
        }

        /**
         * 将特征值转换成Json字符串的格式
         * @return
         */
        public String cluesAsString() {
            try {
                String json = toString(clues);
                return (json==null||json=="") ? EMPTY_FEATURES : PREFIX_OF_FEATURES + json.toString()
                        + SUFFIX_OF_FEATURES;
            } catch (Exception e) {
               
                return EMPTY_FEATURES;
            }
        }
        
        private String toString(Map<String, String> map){
        	
        	 StringBuffer sbuffer=new StringBuffer();
             Set<Map.Entry<String, String>> set = map.entrySet();
             for (Iterator<Map.Entry<String, String>> it = set.iterator(); it.hasNext();) {
            	  Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();	
            	  	sbuffer.append("\"");
            		sbuffer.append(entry.getKey());
            	 	sbuffer.append("\"");
            		sbuffer.append(":");
            	 	sbuffer.append("\"");
            		sbuffer.append(entry.getValue());
            	 	sbuffer.append("\"");
             	}
             	return sbuffer.toString();
             }
        

        /**
         * @see com.alifi.hades.biz.common.LogTracker.getMessage
         * @param prefix
         * @return
         */
        public StringBuilder getMessage(String... prefix) {
            return LogTracker.getMessage(prefix);
        }
    }

    /**
     * 获取用于输出的日志字符串
     * @param prefix
     * @return
     */
    public static StringBuilder getMessage(String... prefix) {
        StringBuilder sb = new StringBuilder();
        for (String str : prefix) {
            sb.append(str);
        }
        sb.append(getLogContext().cluesAsString());
        return sb;
    }

    public static void newLogContext() {
        if (logContextThread == null) {
            logContextThread = new ThreadLocal<LogContext>();
        }

        logContextThread.set(new LogContext());
    }

    public static LogContext getLogContext() {
        if (logContextThread == null || logContextThread.get() == null) {
            newLogContext();
        }
        return logContextThread.get();
    }

    public static void removeLogContext() {
        if (logContextThread != null) {
            logContextThread.remove();
        }
    }
}

